package jprint.jfx;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.Timer;

/**
 * @author zw-zheng
 * Created on 2021-02-05
 */
public class Splash extends JFrame implements AppStarting {

    private static final Color sPgBack = new Color(0xd8d8d8);
    private static final Color sPgFore = new Color(0x1e6fff);
    private static final int sPgHeight = 6;

    private BufferedImage image;
    private int imgWidth;
    private int imgHeight;
    private AtomicBoolean starting = new AtomicBoolean(false);
    private String progressText;
    private int progress;

    Splash() throws HeadlessException {
        setUndecorated(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        try {
            image = ImageIO.read(getClass().getResource("/splash.png"));
            imgWidth = image.getWidth();
            imgHeight = image.getHeight();
            setSize(imgWidth, imgHeight);
            starting.set(true);
            new Thread(this::display, "Thread-Splash").start();
            repaint();
        } catch (IOException e) {
            e.printStackTrace();
            startComplete();
        }
    }

    @Override public void paint(Graphics g) {
        g.drawImage(image, 0, 0, null);
        if (progress > 0) {
            g.setColor(sPgBack);
            g.fillRect(0, imgHeight - sPgHeight, imgWidth, sPgHeight);
            g.setColor(sPgFore);
            g.fillRect(0, imgHeight - sPgHeight, imgWidth * progress / 100, sPgHeight);
        }
        if (progressText != null) {
            g.setColor(Color.BLACK);
            g.drawString(progressText, 4, imgHeight - sPgHeight - 4);
        }
    }

    @Override public void updateProgress(String progressText, double progress) {
        this.progressText = progressText;
        this.progress = (int) Math.min(1, 100 * progress);
    }

    @Override public void startComplete() {
        if (starting.get()) {
            starting.set(false);
            new Timer(500, (evt) -> dispose()).start();
        }
    }

    private void display() {
        while (starting.get()) {
            try {
                Thread.sleep(100);
                repaint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
